`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    15:10:17 04/02/2014 
// Design Name: 
// Module Name:    kbdScan 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module kbdScan(input wire kbd_clk, // Clock pin from keyboard 
					input wire kbd_data, //Data pin form keyboard 
					output reg [7:0] keyCode, //Printing input data to led 
					output reg keyFlag,  // indicates when new key code data scan is complete
					output reg keyRel);  // signal to indicate if a key has been released

	reg [7:0] newData; 	// to store incoming data
	reg [3:0] bitCount; 	//  keeps track which bit is being received
 
	initial begin 
			bitCount<=4'h1; 
			keyFlag<=1'b0;
			newData<=8'h00; 
			keyCode<=8'h00; 
			keyRel<=1'b0;
		end 
 
always @(negedge kbd_clk) //get new data bit with each negedge of keyboard clock
	begin 
		case(bitCount) 
			1:; // start bit 
			2:newData[0]<=kbd_data; 
			3:newData[1]<=kbd_data; 
			4:newData[2]<=kbd_data; 
			5:newData[3]<=kbd_data; 
			6:newData[4]<=kbd_data; 
			7:newData[5]<=kbd_data; 
			8:newData[6]<=kbd_data; 
			9:newData[7]<=kbd_data; 
			10:keyFlag<=1'b1; // parity bit 
			11:keyFlag<=1'b0; // end bit 
		endcase 

		 if(bitCount<=10) 
			bitCount<=bitCount+1'b1; 
		 else if(bitCount==11) 
			bitCount<=1;  
	end

always@(posedge keyFlag) // send key code data to output 
	begin 
		if(newData==8'hf0) 
			keyRel<=1'b1; 
		else begin
		keyCode<=newData;
		keyRel<=1'b0; 
			end
	end

endmodule
 